﻿using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using Missbot.Common;
using Missbot.Common.Net;
using Missbot.Core.Cache;
using Missbot.Core.Scheduler;
using Missbot.Model.MsgCmds.Notes;
using Missbot.Service.Dingtalk;
using Newtonsoft.Json;

namespace Missbot.AIModule.Schedulers.MisskeyUpdateNotice
{
    /// <summary>
    /// github更新定时器
    /// </summary>
    [UsedImplicitly]
    public class UpdateSchedule : IScheduler
    {
        /// <summary>
        /// Github Release地址
        /// </summary>
        private const string ReleaseUrl = "https://api.github.com/repos/syuilo/misskey/releases/latest";
        
        public ILogSvc ILogSvc { get; set; }

        protected override List<ScheduleMeta> ModelList { get; set; }
            = new() {new ScheduleMeta {Span = new IntervalSpan {Interval = TimeSpan.FromHours(1)}, IsImmediately = true}};

        public override string Owner => "iceai";

        protected override void ScheduleDo(SchedulerTimer timer)
        {
            var githubVersion = GetGitHubVersion();
            if (string.IsNullOrEmpty(githubVersion?.TagName))
            {
                return;
            }

            var recVersion = MisskeyUpdateNoticeRecDA.GetLastVersion();
            if (recVersion == githubVersion.TagName)
            {
                return;
            }
            
            DingtalkSvc.Send($"Misskey new Release ({githubVersion.TagName}) is available! Release Rote: {githubVersion.Body}");
            MsgSender.PushMsg(new CreateNoteCmd
                              {
                                  Text = $"***Misskey发布新版本啦！*** \nRelease Version: {githubVersion.TagName}\nRelease Note: {githubVersion.Body}"
                              });
            
            var rec = new MisskeyUpdateNoticeRec {VersionNo = githubVersion.TagName};
            rec.Insert();
        }

        /// <summary>
        /// 获取github最新版本
        /// </summary>
        /// <returns></returns>
        private GithubLatestReleaseResp GetGitHubVersion()
        {
            try
            {
                return HttpRequestor.GetData<GithubLatestReleaseResp>(ReleaseUrl);
            }
            catch (Exception e)
            {
                ILogSvc.LogError(e);
                return default;
            }
        }
    }

    /// <summary>
    /// github最新版本响应体
    /// </summary>
    public class GithubLatestReleaseResp
    {
        [JsonProperty("id")]
        public long ID { get; set; }
        
        [JsonProperty("url")]
        public string Url { get; set; }
        
        [JsonProperty("tag_name")]
        public string TagName { get; set; }
        
        [JsonProperty("created_at")]
        public DateTime CreateAt { get; set; }
        
        [JsonProperty("published_at")]
        public DateTime PublishedAt { get; set; }
        
        [JsonProperty("body")]
        public string Body { get; set; }
    }
}